/*
 * @(#)DocumentStatusTag.java
 *
 * Copyright (c) 2004 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.taglib;

import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TryCatchFinally;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.util.ResponseUtils;

import com.dcivision.alert.bean.UpdateAlert;
import com.dcivision.alert.core.AlertManager;
import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.bean.DmsCheckoutHistory;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsVersion;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.core.DocumentValidateManager;
import com.dcivision.dms.core.VersionControlManager;
import com.dcivision.forum.core.ForumManager;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.PermissionManager;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.taglib.TagUtil;
import com.dcivision.framework.taglib.html.ImgTag;
import com.dcivision.framework.web.WebUtil;
import com.dcivision.workflow.bean.MtmWorkflowProgressSystemObject;
import com.dcivision.workflow.bean.WorkflowRecord;
import com.dcivision.workflow.dao.MtmWorkflowProgressSystemObjectDAObject;
import com.dcivision.workflow.dao.WorkflowRecordDAObject;

/**
 * Taglib to render the status of a DmsDocument (Expired/Checked Out...etc)
 *
 * @author  Lun Au
 * @company DCIVision Limited
 * @date    2007-05-06
 * @version $Revision: 1.1.2.17 $
 */
public class DocumentStatusTag extends ImgTag implements TryCatchFinally {

  private static final Log log = LogFactory.getLog(DocumentStatusTag.class);

  public final static String DMS_LOCKED_IMAGE = "IconDMSLock.gif";

  public final static String DMS_UNLOCK_IMAGE = "IconDMSUnlock.gif";

  public final static String DMS_NO_PERMISSION_IMAGE = "IconDMSNoReadPermission.gif";
  
  public final static String DMS_BIND_WORKFLOW_IMAGE = "IconDMSBindWorkflow.gif";
  
  public final static String DMS_EXPIRED_IMAGE = "IconDMSExpired.gif";
  
  public final static String DMS_NOT_YET_EFFECTIVE_IMAGE = "IconDMSExpired.gif";

  public final static String DMS_ALERT_EDIT_IMAGE = "IconDMSAlertEdit.gif";

  public final static String DMS_DISCUSSION_IMAGE = "IconDMSDiscussion.gif";

  protected SessionContainer sessionContainer = null;

  protected Connection conn = null;

  protected String contextPath = null;

  protected String imageBase = null;

  protected DmsDocument dmsDocument = null;

  protected DmsDocument targetDmsDocument = null;

  protected String sCurFunctionCode = null;

  protected String permissionString = null;

  private String[] showStatusItems = null;
  
  private boolean isInvitedToRead = false;
  
  private boolean hasReadPermission = false;
  
  private String target = null;
  
  protected static final int TARGET_SELF = 0;
  
  protected static final int TARGET_OPENER = 1;

  protected static final int TARGET_PARENT = 2;
  /**
   * @return the showStatusItems
   */
  public String[] getShowStatusItems() {
    return showStatusItems;
  }

  /**
   * @return the target
   */
  public String getTarget() {
    return target;
  }

  /**
   * @param target the target to set
   */
  public void setTarget(String target) {
    this.target = target;
  }

  /**
   * @param showStatusItems the showStatusItems to set
   */
  public void setShowStatusItems(String[] showStatusItems) {
    this.showStatusItems = showStatusItems;
  }

  /**
   * @return the isInvitedToRead
   */
  public boolean isInvitedToRead() {
    return isInvitedToRead;
  }

  /**
   * @param isInvitedToRead the isInvitedToRead to set
   */
  public void setInvitedToRead(boolean isInvitedToRead) {
    this.isInvitedToRead = isInvitedToRead;
  }
  
  protected int getTargetType() {
    if (Utility.isEmpty(getTarget())) {
      return TARGET_SELF;
    }
    
    if ("opener".equals(getTarget())) {
      return TARGET_OPENER;
    }
    
    if("parent".equals(getTarget())){
      return TARGET_PARENT;
    }
    
    return TARGET_SELF;
  }

  public int doEndTag() throws JspException {
    try {
      ResponseUtils.write(pageContext, renderDocumentStatus());
    } catch (ApplicationException ae) {
      log.error("Errors occur in generating document status.", ae);
      throw new JspException(ae);
    } finally{
      this.release();
    }
    
    return EVAL_PAGE;
  }

  public int doStartTag() throws JspException {
    if (Utility.isEmpty(dmsDocument)){
      dmsDocument = (DmsDocument) pageContext.getAttribute(DmsOperationConstant.DMS_DOCUMENT_BEAN);  
    }    
    hasReadPermission = false;
    this.init();
    return EVAL_BODY_BUFFERED;
  }

  protected boolean isExpired() {
    if (targetDmsDocument.getEffectiveEndDate() == null) {
      return false;
    }
    
    boolean isExpired = true;
    Timestamp nowTime = Utility.getCurrentTimestamp();
    Timestamp oneDayBeforeCurrTime = Utility.addDay(nowTime, -1);
    if (isExpired && (targetDmsDocument.getEffectiveStartDate()==null || targetDmsDocument.getEffectiveStartDate().equals(nowTime) || targetDmsDocument.getEffectiveStartDate().before(nowTime))
        && (targetDmsDocument.getEffectiveEndDate()==null || targetDmsDocument.getEffectiveEndDate().equals(nowTime) || targetDmsDocument.getEffectiveEndDate().after(oneDayBeforeCurrTime))) {
     isExpired=false;
   }

    return isExpired;
  }
  
  protected boolean isNotYetEffective() {
    if (targetDmsDocument.getEffectiveStartDate() == null) {
      return false;
    }
    
    boolean isNotYetEffective = false;
    
    if (targetDmsDocument.getEffectiveStartDate().getTime() >= Utility.getCurrentTimestamp().getTime()) {
      isNotYetEffective = true;
    }
    
    return isNotYetEffective;
  }

  protected boolean isAlertEdit() throws ApplicationException {
    boolean isAlertEdit = false;

    AlertManager am = new AlertManager(sessionContainer, conn);
    if (targetDmsDocument.getAlertEditID() != null) {
      isAlertEdit =  am.checkAlertOwner(targetDmsDocument.getID(), sessionContainer.getUserRecordID(), null);
    }
    am.release();

    return isAlertEdit;
  }

  protected boolean isDiscussion() throws ApplicationException {

    if (isExpired()) {
      return false;
    }

    boolean isDiscussion = false;
    
    ForumManager forumManager = new ForumManager(sessionContainer, conn);
    if (forumManager.hasDiscussion(GlobalConstant.OBJECT_TYPE_DOCUMENT, targetDmsDocument.getID())) {
      isDiscussion = true;
    }

    return isDiscussion;
  }
  
  protected boolean hasReadPermission() {
    return hasReadPermission;
  }
  
  protected boolean isBindWithWorkflow() throws ApplicationException {
    MtmWorkflowProgressSystemObjectDAObject mtmWfProgressSysObjDAO = new MtmWorkflowProgressSystemObjectDAObject(sessionContainer, conn);
    List relatedWorkflow = mtmWfProgressSysObjDAO.getListByBeanClassNameObjectID(DmsDocument.class.getName(), targetDmsDocument.getID());
    return (Utility.isEmpty(relatedWorkflow) ? false : true);
  }
  
  protected boolean isSelected2Show(String documentStatus) {

    if (Utility.isEmpty(showStatusItems)) {
      return true;
    }

    boolean isSelected = false;

    for (int i = 0; i < showStatusItems.length; i++) {
      String item = showStatusItems[i];
      if (item.equals(documentStatus)) {
        isSelected = true;
        break;
      }
    }

    return isSelected;
  }

  protected StringBuffer generateDocumentStatus(String documentStatus) throws JspException {
    StringBuffer statusContent = new StringBuffer();

    if (DmsVersion.EXCLUSIVE_LOCK.equals(documentStatus)) {
      statusContent.append(renderLockStatus());
    }

    if ("EXPIRED_STATUS".equals(documentStatus)) {
      statusContent.append(renderExpiredStatus());
    }
    
    if ("NOT_YET_EFFECTIVE_STATUS".equals(documentStatus)) {
      statusContent.append(renderNotYetEffectiveStatus());
    }
    
    if ("NO_READ_PERMISSION_STATUS".equals(documentStatus)) {
      statusContent.append(renderNoReadPermissionStatus());
    }
    
    if ("BIND_WORKFLOW_STATUS".equals(documentStatus)) {
      statusContent.append(renderBindWorkflowStatus());
    }

    if ("ALERT_EDIT_STATUS".equals(documentStatus)) {
      statusContent.append(renderAlertEditStatus());
    }

    if ("DISCUSSION_STATUS".equals(documentStatus)) {
      statusContent.append(renderDiscussionStatus());
    }

    return statusContent;
  }
  
  protected String renderExpiredStatus() throws JspException {
    StringBuffer buffer = new StringBuffer();
    
    buffer.append(
        "<a " +
        "  href=\"#\" onclick=\"return false;\"" +
        "  onmouseover=\"return getDocumentInfo('"
           + TextUtility.escapeJSString(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "dms.message.document_is_expired")) +
           "')\" " +
        "  onmouseout=\"return nd()\"" +
        ">"
        + renderImage(DMS_EXPIRED_IMAGE) +
        "</a>"
        );
    
    return buffer.toString();
  }
  
  protected String renderNotYetEffectiveStatus() throws JspException {
    StringBuffer buffer = new StringBuffer();
    
    buffer.append(
        "<a " +
        "  href=\"#\" onclick=\"return false;\"" +
        "  onmouseover=\"return getDocumentInfo('"
           + TextUtility.escapeJSString(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "dms.message.document_not_yet_effective")) +
           "')\" " +
        "  onmouseout=\"return nd()\"" +
        ">"
        + renderImage(DMS_NOT_YET_EFFECTIVE_IMAGE) +
        "</a>"
    );
    
    return buffer.toString();
  }
  
  protected String renderNoReadPermissionStatus() throws JspException {
    StringBuffer buffer = new StringBuffer();
    
    buffer.append(
        "<a " +
        "  href=\"#\" onclick=\"return false;\"" +
        "  onmouseover=\"return getDocumentInfo('"
           + TextUtility.escapeJSString(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "dms.message.document_no_read_permission")) +
           "')\" " +
        "  onmouseout=\"return nd()\"" +
        ">"
        + renderImage(DMS_NO_PERMISSION_IMAGE) +
        "</a>"
    );
    
    return buffer.toString();
  }
  
  protected String renderLockStatus() throws JspException {
    StringBuffer buffer = new StringBuffer();
    
    try {
      VersionControlManager verControlManager = new VersionControlManager(sessionContainer, conn);
      DmsCheckoutHistory checkoutHistory = verControlManager.getCheckoutHistory(targetDmsDocument.getCheckoutID());
      Integer checkoutPersonID = checkoutHistory.getCheckoutPersonID();
      String checkoutUser = UserInfoFactory.getUserFullName(checkoutPersonID);
      // Check out or check in using the status icon is confirmed to be disabled from UI by BA team
      
      String targetURL = "";
      StringBuffer onclickContent = new StringBuffer();     
      if(checkoutPersonID.equals(sessionContainer.getUserRecordID())){
        targetURL = WebUtil.getContextPath(pageContext) + "/dms/MaintDmsCheckout.do?" + "opMode=DMS.CHECKOUT_CHECK&documentID="
        + targetDmsDocument.getID() + "&ID=" + targetDmsDocument.getParentID() + "&parentID=" + targetDmsDocument.getParentID()
        + "&rootID=" + targetDmsDocument.getRootID() + "" + "&curFunctionCode=" + SystemFunctionConstant.DMS_PUBLIC_FOLDER
        + "&directPage=" + DmsOperationConstant.LIST_PUBLIC_PAGE;
        onclickContent.append(getOnclickContent(targetURL));
      }
      buffer.append(
          "<a " +
          "  href=\"#\" " +
          "  onmouseover=\"return getDocumentInfo('"
             + TextUtility.escapeJSString(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "dms.label.checked_out_by", checkoutUser)) +
             "')\" " +
          "  onmouseout=\"return nd()\" " +
          "  onclick=\"" + onclickContent + "\"" +
          ">"
          + renderImage(DMS_LOCKED_IMAGE) +
          "</a>"
      );
    } catch (ApplicationException ape) {
      throw (new JspException("Errors occur at rendering bind workflow status!", ape));
    }
    
    return (buffer.toString());
  }
  
  protected String renderAlertEditStatus() throws JspException {
    StringBuffer buffer = new StringBuffer();
    
    String targetURL = WebUtil.getContextPath(pageContext) + "/dms/MaintDmsUpdateAlert.do?" + "navMode=" + GlobalConstant.NAV_MODE_VIEW
        + "&alertType=" + UpdateAlert.ALERT_TYPE + "&documentType=" + targetDmsDocument.getDocumentType() + "&objectID="
        + targetDmsDocument.getID() + "&parentID=" + targetDmsDocument.getParentID() + "&rootID=" + targetDmsDocument.getRootID()
        + "&curFunctionCode=" + SystemFunctionConstant.DMS_PUBLIC_FOLDER;
    
    StringBuffer onclickContent = new StringBuffer();
    onclickContent.append(getOnclickContent(targetURL));    
    buffer.append(
        "<a " +
        "  href=\"#\" " +
        "  onmouseover=\"return getDocumentInfo('"
           + TextUtility.escapeJSString(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "dms.label.alert_enabled")) +
           "')\" " +
        "  onmouseout=\"return nd()\" " +
        "  onclick=\"" + onclickContent + "\"" +
        ">"
        + renderImage(DMS_ALERT_EDIT_IMAGE) +
        "</a>"
    );
    
    return (buffer.toString());
  }
  
  protected String renderBindWorkflowStatus() throws JspException {
    StringBuffer buffer = new StringBuffer();
    
    try {
      DocumentValidateManager docValidateManager = new DocumentValidateManager(sessionContainer,conn);
      MtmWorkflowProgressSystemObjectDAObject mtmWfProgressSysObjDAO = new MtmWorkflowProgressSystemObjectDAObject(sessionContainer, conn);
      WorkflowRecordDAObject workflowRecordDAO = new WorkflowRecordDAObject(sessionContainer, conn);
      
      List relationshipWithWorkflowList = mtmWfProgressSysObjDAO.getListByBeanClassNameObjectID(DmsDocument.class.getName(), targetDmsDocument.getID());
      for (Iterator relationShipItems = relationshipWithWorkflowList.iterator(); relationShipItems.hasNext();) {
        MtmWorkflowProgressSystemObject relationShipItem = (MtmWorkflowProgressSystemObject) relationShipItems.next();
        WorkflowRecord relatedWorkflow = (WorkflowRecord) workflowRecordDAO.getObjectByTrackID(relationShipItem.getTrackID());
        
        boolean isRenderLink = (docValidateManager.checkPermissionToShowWfIcon(relatedWorkflow.getWorkflowGroupID()) && hasReadPermission());
        if (isRenderLink) {
          buffer.append(
              "<a href=\"#\" " +
              "  onmouseover=\"return getDocumentInfo('"
                 + TextUtility.escapeJSString(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "dms.label.related_to_workflow", relatedWorkflow.getWorkflowCode())) +
                 "')\" " +
              "  onmouseout=\"return nd()\" " +
              "  onclick=\"OpenCenteredPopup('"
                 + WebUtil.getContextPath(pageContext) + "/workflow/PreviewWorkflowRecord.do?ID=" + relatedWorkflow.getID() + "&trackID=" + relationShipItem.getTrackID()
                 + "', 'DCIVisionWFRelation', 750, 500, 'scrollbars=yes'); return false;\"" +
              ">"
          );
        }
        buffer.append(renderImage(DMS_BIND_WORKFLOW_IMAGE));
        if (isRenderLink) {
          buffer.append("</a>");
        }
      }
    } catch (ApplicationException ape) {
      throw (new JspException("Errors occur at rendering bind workflow status!", ape));
    }
    
    return (buffer.toString());
  }
  
  protected String renderDiscussionStatus() throws JspException {
    StringBuffer buffer = new StringBuffer();
    
    try {
      boolean isRenderLink = (GlobalConstant.STATUS_ACTIVE.equals(targetDmsDocument.getRecordStatus())
          && !isExpired() && permissionString.indexOf("U") >= 0);
      
      if (isRenderLink) {
        ForumManager forumManager = new ForumManager(sessionContainer, conn);
        
        String returnToURL = "ListDmsPublicDocument.do?opMode="
          + GlobalConstant.OP_MODE_LIST_RETAIN +
          "&rootID=" + targetDmsDocument.getRootID() + "&parentID=" + targetDmsDocument.getParentID() + 
          "&curFunctionCode=" + SystemFunctionConstant.DMS_PUBLIC_FOLDER;
        returnToURL = URLEncoder.encode(returnToURL);
        
        String totalTopic = String.valueOf(forumManager.getTopicTotalByObject(
            GlobalConstant.OBJECT_TYPE_DOCUMENT, targetDmsDocument.getID()));
        String totalReply = String.valueOf(forumManager.getReplyTotalByObject(
            GlobalConstant.OBJECT_TYPE_DOCUMENT, targetDmsDocument.getID().toString()));
        
        String targetURL = WebUtil.getContextPath(pageContext) + "/dms/ListDmsForum.do?" + "objectType="
            + GlobalConstant.OBJECT_TYPE_DOCUMENT + "&objectID=" + targetDmsDocument.getID() + "&rootID=" + targetDmsDocument.getRootID()
            + "&parentID=" + targetDmsDocument.getParentID() + "&curFunctionCode=" + SystemFunctionConstant.DMS_PUBLIC_FOLDER
            + "&returnTo=" + returnToURL;
        
        StringBuffer onclickContent = new StringBuffer();
        onclickContent.append(getOnclickContent(targetURL));
        buffer.append(
            "<a " +
            "  href=\"#\" " +
            "  onmouseover=\"return getDocumentInfo('"
               + TextUtility.escapeJSString(MessageResourcesFactory.getMessage(
                   sessionContainer.getSessionLocale(), "forum.lable.includes_replies_and_reads", new String[] {totalTopic, totalReply})) +
               "')\" " +
            "  onmouseout=\"return nd()\" " +
            "  onclick=\"" + onclickContent + "\"" +
            ">"
        );
      }
      
      buffer.append(renderImage(DMS_DISCUSSION_IMAGE));
      
      if (isRenderLink) {
        buffer.append("</a>");
      }
    } catch (ApplicationException ape) {
      throw (new JspException("Errors occur at rendering discussion status!", ape));
    }

    return (buffer.toString());
  }

  protected String renderDocumentStatus() throws ApplicationException, JspException {

    if ("PERSONAL".equals(permissionString)) {
      return (GlobalConstant.EMPTY_FIELD);
    }
    
    PermissionManager permissionManager = sessionContainer.getPermissionManager();

    List documentStatusList = new ArrayList();

    if (targetDmsDocument != null) {
      if (!hasReadPermission()) {//if no access right ,could not co-exist with other icons, hide all the other icons..
        documentStatusList.add("NO_READ_PERMISSION_STATUS");
      } else if (isNotYetEffective()) {
        documentStatusList.add("NOT_YET_EFFECTIVE_STATUS");
        if (isBindWithWorkflow() && (targetDmsDocument.getCreatorID().equals(sessionContainer.getUserRecordID()) || targetDmsDocument.getOwnerID().equals(sessionContainer.getUserRecordID()) ) ) {
          documentStatusList.add("BIND_WORKFLOW_STATUS");
        }
      } else if (isExpired()) {
        documentStatusList.add("EXPIRED_STATUS");
        if (isBindWithWorkflow() && (targetDmsDocument.getCreatorID().equals(sessionContainer.getUserRecordID()) || targetDmsDocument.getOwnerID().equals(sessionContainer.getUserRecordID()) ) ) {
          documentStatusList.add("BIND_WORKFLOW_STATUS");
        }
      } else {
        if (permissionManager.getPermission(GlobalConstant.OBJECT_TYPE_DOCUMENT, targetDmsDocument.getID()).indexOf(DmsOperationConstant.DMS_PERMISSION_ALLOW_UPDATE_DOCUMENT) > 0){
          documentStatusList.add(targetDmsDocument.getItemStatus());
        }
        if (isBindWithWorkflow()) {
          documentStatusList.add("BIND_WORKFLOW_STATUS");
        }
        if (isAlertEdit() && permissionManager.getPermission(GlobalConstant.OBJECT_TYPE_DOCUMENT, targetDmsDocument.getID()).indexOf(DmsOperationConstant.DMS_PERMISSION_ALLOW_SET_ALERT) > 0) {
          documentStatusList.add("ALERT_EDIT_STATUS");
        }
        if (isDiscussion() && permissionManager.getPermission(GlobalConstant.OBJECT_TYPE_DOCUMENT, targetDmsDocument.getID()).indexOf(DmsOperationConstant.DMS_PERMISSION_ALLOW_DISCUSSION) > 0) {
          documentStatusList.add("DISCUSSION_STATUS");
        }
      }
    }

    StringBuffer sb = new StringBuffer();
    sb.append("<div class='selectionStatus'>");
    for (int i = 0; i < documentStatusList.size(); i++) {
      String statues = (String) documentStatusList.get(i);
      if (!isSelected2Show(statues)) {
        continue;
      }

      sb.append(generateDocumentStatus(statues));
    }
    sb.append("</div>");
    return (sb.toString());
  }

  public String renderImage(String image) throws JspException {
    ImgTag imgTag = new ImgTag();
    imgTag.setCommon(true);
    imgTag.setCustomize(false);
    imgTag.setSrc(image);
    String imageHTML = TagUtil.renderTag(pageContext, imgTag);
    return (imageHTML);
  }
  
  protected void initPermission() throws ApplicationException {
    if (GlobalConstant.RECORD_STATUS_INACTIVE.equals(targetDmsDocument.getRecordStatus())) {
      hasReadPermission = false;
      return;
    }
    
    String permissionValue = sessionContainer.getPermissionManager().getPermission(GlobalConstant.OBJECT_TYPE_DOCUMENT, targetDmsDocument.getID());
    if (PermissionManager.isContainsReadPermission(permissionValue) || isInvitedToRead) {
      hasReadPermission = true;
    }
  }

  protected void init() {
    sessionContainer = (SessionContainer) this.pageContext.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY);
    conn = (Connection) pageContext.getRequest().getAttribute(GlobalConstant.DB_KEY);
    contextPath = (String) this.pageContext.getServletContext().getAttribute(GlobalConstant.CONTEXT_PATH_KEY);

    sCurFunctionCode = (String) pageContext.getRequest().getAttribute(GlobalConstant.FUNCTION_CODE_KEY);

    PermissionManager permissionManager = sessionContainer.getPermissionManager();
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    DmsDocument documentRoot = null;

    try {
      // If current dmsDocument is a shortcut, display its target document status.
      if (DmsDocument.DOCUMENT_LINK.equals(dmsDocument.getDocumentType())) {
        targetDmsDocument = docRetrievalManager.getRelationshipTargetDocument(dmsDocument.getID(), dmsDocument.getDocumentType(), GlobalConstant.RECORD_STATUS_ACTIVE);
      } else {
        targetDmsDocument = dmsDocument;
      }

      if (targetDmsDocument != null) {
        documentRoot = docRetrievalManager.getRootFolderByRootID(targetDmsDocument.getRootID());
        if (documentRoot != null) {
          if (DmsOperationConstant.DMS_PERSONAL_ROOT.equals(documentRoot.getDocumentName())) {
            permissionString = "PERSONAL";
            sCurFunctionCode = SystemFunctionConstant.DMS_PERSONAL_FOLDER;
          } else {
            // Bill add for EIP-2028
            permissionString = permissionManager.filterDocumentPermissionByWorkflow(conn, GlobalConstant.OBJECT_TYPE_DOCUMENT, dmsDocument
                .getID());
            sCurFunctionCode = SystemFunctionConstant.DMS_PUBLIC_FOLDER;
          }
        }
        
        initPermission();
      } else {
        log.warn("targetDmsDocument is null, dmsDocument id=" + dmsDocument.getID());
      }
    } catch (ApplicationException ae) {
      log.error(ae.getMessage(), ae);
      throw new RuntimeException(ae);
    }

    super.init();
  }
  
  private String getOnclickContent(String targetURL){
    if(Utility.isEmpty(targetURL)){
      return "";
    }
    StringBuffer sb = new StringBuffer();
    if (TARGET_SELF == getTargetType()) {
      sb.append("location.href='" + TextUtility.escapeJSString(targetURL) + "';return false;");
    }

    if (TARGET_OPENER == getTargetType()) {
      sb.append("window.opener.location.href='" + TextUtility.escapeJSString(targetURL) + "';window.close();");
    }
    
    if(TARGET_PARENT == getTargetType()){
      sb.append("CancelInvitationShow();"+"window.parent.location.href='" + TextUtility.escapeJSString(targetURL) + "';window.close();");
    }
    return sb.toString();
  }

  public void release() {
    super.release();
    sCurFunctionCode = null;
    permissionString = null;
    targetDmsDocument = null;
    showStatusItems = null;
    target = null;
    dmsDocument = null;
  }

  public DmsDocument getDmsDocument() {
    return dmsDocument;
  }

  public void setDmsDocument(DmsDocument dmsDocument) {
    this.dmsDocument = dmsDocument;
  }

  public void doCatch(Throwable t) throws Throwable {
    throw t;
  }

  public void doFinally() {
    release();
  }

}
